﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Entities;
using System.Web.Security;
using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Services.Concrete;
using DataAccess.Repositories;
using BusinessLayer;


namespace DataAccess.Services.Abstract
{
    /// <summary>
    /// Servicio de login
    /// </summary>
    public class LoginService : ILoginService
    {
        /// <summary>
        /// Comprueba las credenciales del usuario y procede a logearlo si está autorizado.
        /// </summary>
        /// <param name="username">Nombre de usuario</param>
        /// <param name="password">Contraseña</param>
        /// <returns>true si pudo logearse, de lo contrario false</returns>
        public bool LoginUser(string username, string password)
        {
            IAccountRepository accountRepository = new AccountRepository();
            SessionService sessionService = new SessionService();

            string encryptedPassword = 
                FormsAuthentication.HashPasswordForStoringInConfigFile(password, 
                                                Constants.EncryptionMethod);
            try
            {
                Account user = accountRepository.FetchByUsername(username);

                if (user.Password == encryptedPassword)
                {
                    sessionService.CurrentLoggedUser = user;
                    sessionService.UserLoggedIn = true;
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
    }
}
